<template>
  <view>
    <u-picker
      @cancel="showLocal = false"
      @close="showLocal = false"
      :show="showLocal"
      :columns="addressColumns"
      @confirm="localConfirm"
      title="请选择所在地"
      keyName="name"
      itemHeight="80"
      closeOnClickOverlay
      ref="uPicker"
      @change="changeHandler"
      :defaultIndex="defaultAddress"
      immediateChange
    ></u-picker>
  </view>
</template>

<script>
import areas from "../../data/areas.json";

export default {
  data() {
    return {
      showLocal: false,
      addressColumns: [], //数据数组
      defaultAddress: [], //默认选中 (回填时或者初次显示默认选中)
      addressData: areas //原始数据 (引入的json文件)
    };
  },

  created() {
    //省的数组
    const provinceData = areas.map(e => {
      return { name: e.name, code: e.code }; //这里可以直接return e.name  这里我是要用到code所以才用对象包起来的 下面的市 区 也一样
    });
    //市的数组
    const cityData = areas.map(e => {
      const arr = [];
      arr.push(
        e.areas.map(c => {
          return { name: c.name, code: c.code };
        })
      );
      return arr;
    });
    //区的数组
    const areaData = areas.map(e => {
      const arr = [];
      arr.push(
        e.areas.map(c =>
          c.areas.map(d => {
            return { name: d.name, code: d.code };
          })
        )
      );
      return arr;
    });
    const arr = [provinceData, cityData[0][0], areaData[0][0][0]];
    this.addressColumns = arr; //将得到的3个数组 的第一个市的所有数据赋值 作为初始数据
  },
  methods: {
    init() {
      this.showLocal = true;
    },
    hide() {
      this.showLocal = false;
    },
    localConfirm(e) {
      this.$emit("localConfirm", e);
    },
    changeHandler(e) {
      //分别表示选中的列 , 该列的第几个,选中的3列的第几个的数组,组件本身
      const { columnIndex, index, indexs, picker = this.$refs.uPicker } = e;
      //如果改变的是第一列
      if (columnIndex === 0) {
        const children1 = this.addressData[index].areas.map(e => {
          return { name: e.name, code: e.code };
        });
        picker.setColumnValues(1, children1);
        //更换 第二列数据
        const children2 = this.addressData[index].areas[indexs[1]].areas.map(e => {
          return { name: e.name, code: e.code };
        });
        picker.setColumnValues(2, children2);
        //更换 第三列数据
      }
      if (columnIndex === 1) {
        //如果改变的是第二列
        const children3 = this.addressData[indexs[0]].areas[indexs[1]].areas.map(e => {
          return { name: e.name, code: e.code };
        });
        picker.setColumnValues(2, children3);
        //更换 第三列数据
      }
    }
  }
};
</script>

<style lang="scss" scoped></style>
